package com.ruiao.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruiao.car.dto.ArticlesPraiseDto;
import com.ruiao.car.dto.ResultDto;
import com.ruiao.car.entity.Praise;
import com.ruiao.car.enums.IResultEnum;
import com.ruiao.car.enums.ResultEnum;
import com.ruiao.car.mapper.PraiseMapper;
import com.ruiao.car.service.IPraiseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruiao.car.utils.AccountHeaderUtil;
import com.ruiao.car.utils.AccountThreadLocal;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 点赞 服务实现类
 * </p>
 *
 * @author jsonval@163.com
 * @since 2020-06-16
 */
@Service
public class PraiseServiceImpl extends ServiceImpl<PraiseMapper, Praise> implements IPraiseService {

    @Override
    public ResultDto addPraise(ArticlesPraiseDto dto) {
        AccountHeaderUtil accountThreadLocal =  AccountThreadLocal.get();
        Praise praise = this.getOne(Wrappers.<Praise>query().lambda()
                .eq(Praise::getAccountId,accountThreadLocal.getAccount().getId())
                .eq(Praise::getArticlesId,dto.getArticlesId())
                .eq(Praise::getPraiseStatus,1));
        if(praise == null){
            praise = Praise.builder()
                    .appId(accountThreadLocal.getHeaderUtil().getAppId())
                    .accountId(accountThreadLocal.getAccount().getId())
                    .accountName(accountThreadLocal.getAccount().getNickName())
                    .articlesId(dto.getArticlesId())
                    .build();
            this.save(praise);
            return ResultDto.get(ResultEnum.SUCCESS);
        }
        return new ResultDto(ResultEnum.SUCCESS.getErrCode(),"已点赞");
    }

    @Override
    public ResultDto deletePraise(ArticlesPraiseDto dto) {
        Praise praise = this.getOne(new QueryWrapper<Praise>().lambda().
                eq(Praise::getAccountId,AccountThreadLocal.get().getAccount().getId())
                .eq(Praise::getArticlesId,dto.getArticlesId())
                .eq(Praise::getPraiseStatus,1));
        if(null!=praise){
            praise.setUpdateDate(new Date());
            praise.setPraiseStatus(Byte.valueOf("0"));
            this.updateById(praise);
        }
        return ResultDto.get(ResultEnum.SUCCESS);
    }
}
